﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;
using TPOJ.Model;
using TPOJ.BLL;
using System.Web.Caching;
using TPOJ.CacheDependencyFactory;

namespace TPOJ.Web
{
    public static class ProblemDataProxy
    {
        private static readonly int problemTimeout = int.Parse(ConfigurationManager.AppSettings["ProblemCacheDuration"]);
        private static readonly bool enableCaching = bool.Parse(ConfigurationManager.AppSettings["EnableCaching"]);

        public static IList<Problem> GetAllProblems()
        {
            ProblemBO problemBO = new ProblemBO();

            if (!enableCaching)
                return problemBO.GetAllProblems();

            string key = "problem_all";
            IList<Problem> data = (IList<Problem>)HttpRuntime.Cache[key];

            if (data == null)
            {
                data = problemBO.GetAllProblems();

                AggregateCacheDependency aggrCacheDependency = DependencyFacade.GetProblemDependency();

                HttpRuntime.Cache.Add(key, data, aggrCacheDependency, DateTime.Now.AddHours(problemTimeout), Cache.NoSlidingExpiration, CacheItemPriority.High, null);
            }
            return data;
        }

        public static IList<Problem> GetProblemsByVolume(int volumeId)
        {
            ProblemBO problemBO = new ProblemBO();

            if (!enableCaching)
                return problemBO.GetProblemsByVolume(volumeId);

            string key = "problem_volume" + volumeId;

            IList<Problem> data = (IList<Problem>)HttpRuntime.Cache[key];

            if (data == null)
            {
                data = problemBO.GetProblemsByVolume(volumeId);

                AggregateCacheDependency aggrCacheDependency = DependencyFacade.GetProblemDependency();

                HttpRuntime.Cache.Add(key, data, aggrCacheDependency, DateTime.Now.AddHours(problemTimeout), Cache.NoSlidingExpiration, CacheItemPriority.High, null);
            }
            return data;
        }

        public static Problem GetProblem(int id)
        {
            ProblemBO problemBO = new ProblemBO();

            if (!enableCaching)
                return problemBO.GetProblem(id);

            string key = "problem" + id;
            Problem data = (Problem)HttpRuntime.Cache[key];

            if (data == null)
            {
                data = problemBO.GetProblem(id);

                AggregateCacheDependency aggrCacheDependency = DependencyFacade.GetProblemDependency();

                HttpRuntime.Cache.Add(key, data, aggrCacheDependency, DateTime.Now.AddHours(problemTimeout), Cache.NoSlidingExpiration, CacheItemPriority.High, null);
            }
            return data;
        }
    }
}
